<?php

class OAuthUtils {
    
    /**
     * @method-name : getLang().
     * @parameter   : NULL
     * @return      : string
     * @author  : stephen.mo
     * @date    : 2010/09/13
     */
    static public function getLang() {/*{{{*/
        $cookie_lang  = (isset($_COOKIE['m_tvb_lang']) && !empty($_CCOKIE['m_tvb_lang'])) ? $_COOKIE['m_tvb_lang'] : NULL; 
        $lang = self::chkLang($cookie_lang);
        return $lang;
    }/*}}}*/
 
    /**
     * @method-name : setLang().
     * @parameter   : (string)$lang
     * @return      : string
     * @author  : stephen.mo
     * @date    : 2010/09/13
     */   
    static public function setLang($lang='zh-hant-hk') {/*{{{*/
        $lang = (isset($lang) && !empty($lang)) ? $lang : OAuthConfig::DEFAULT_SUPPORT_LANG;
        $lang = chkLang($lang);
        setcookie('m_tvb_lang',$lang,OAuthConfig::SET_COOKIE_EXPIRE_TIME*60+time(),"/",".tvb.com");
        return TRUE;
    }/*}}}*/
    
    /**
     * @method-name : chkIsLogin().
     * @parameter   : (string)$login_id - tvb.com member's login id.
     * @parameter   : (string)$oauth_token - from app to browser.
     * @parameter   : (string)$lid - a encrypt member_id string.
     * @return      : mixed
     * @author      : stephen.mo <stephen.mo@achievo.com>
     * @date        : Dec 8,2010
     */
    static public function chkIsLogin($login_id=NULL,$oauth_token=NULL,$lid=NULL) {/*{{{*/
        if (!empty($lid)) {
            $token = self::decrypt($lid);
            if (empty($token) || !isset($token['member_id']) || empty($token['member_id']) || (isset($token['time']) && (time()-$token['time'])>0)) {
                return FALSE;
            }
            $userInfo = OAuthUtils::getUserInfoFromMc($token['member_id']);
            if (empty($userInfo) || !isset($userInfo['login_id']) || empty($userInfo['login_id'])) return FALSE;
            if (!empty($userInfo) && isset($userInfo['login_id'])) {
               $login_id = $userInfo['login_id']; 
            }

            if (!isset($login_id) && empty($login_id)) return FALSE;
        }
        
        $userInfo = (isset($userInfo) && !empty($userInfo)) ? $userInfo : (!empty($login_id) && !empty($oauth_token)) ? OAuthUtils::getUserInfoFromMc($login_id) : NULL;
        if (!empty($userInfo) && isset($userInfo['access_token']) && 0==strcmp($userInfo['access_token'],$oauth_token)) {
            if (!isset($_COOKIE['mm_tvb_email']) || empty($_COOKIE['mm_tvb_email'])) {
                $lang  = (isset($_COOKIE['m_tvb_lang']) && !empty($_COOKIE['m_tvb_lang'])) ? self::chkLang($_COOKIE['m_tvb_lang']) : self::getLang();
                $email = (isset($userInfo['user']) && !empty($userInfo['user'])) ? $userInfo['user'] : NULL;
                if (!empty($email)) self::saveLoginInfo($email,$lang);
                return TRUE;
            }
        }

        if (!empty($userInfo) && !empty($login_id)) {
            $rev = self::chkSSOLoginStatus($userInfo['token'],$login_id);
            if ($rev == 2) {
                $users = self::getUserInfoByLoginId($login_id);
                $email = (isset($_COOKIE['m_tvb_lang']) && !empty($_COOKIE['m_tvb_lang'])) ? $_COOKIE['mm_tvb_email'] : $userInfo['user'];
                $lang  = (isset($_COOKIE['m_tvb_lang']) && !empty($_COOKIE['m_tvb_lang'])) ? $_COOKIE['m_tvb_lang'] : (isset($users->result->lang) ? $users->result->lang : self::chkLang());
                self::saveLoginInfo($email,$lang);
                return TRUE;
            }
        }
        if (isset($_COOKIE['mm_tvb_email']) && !empty($_COOKIE['mm_tvb_email'])) {
            return TRUE;
        }
        return FALSE;
    }/*}}}*/
    
    /**
     * @method-name : getEmailByCookie()
     * @parameter   : NULL
     * @description : get user's email from cookie.
     * @return      : string
     * @author      : stephen.mo <stephen.mo@achievo.com>
     * @date        : Dec 8,2010
     */
    static public function getEmailByCookie() {/*{{{*/
        if (isset($_COOKIE['mm_tvb_email']) && !empty($_COOKIE['mm_tvb_email'])) {
            return $_COOKIE['mm_tvb_email'];
        }
        return NULL;
    }/*}}}*/

    /**
     * @method-name : getDefaultLoginId()
     * @parameter   : (string)$login_id - member's login id.
     * @description : get default login id by cookie ,when user is logined.
     * @return      : string 
     * @author      : stephen.mo <stephen.mo@achievo.com>
     * @date        : Dec 8,2010
     */
    static public function getDefaultLoginId($login_id=NULL) {/*{{{*/
        if (!empty($login_id)) {
            $token = self::decrypt($login_id);
            if (!empty($token) && isset($token['member_id']) && ($token['time'] - time())>0){
                $userInfo = OAuthUtils::getUserInfoFromMc($token['member_id']);
                if (!empty($userInfo) && isset($userInfo['login_id'])) {
                    $login_id = $userInfo['login_id'];
                    $rev = self::chkSSOLoginStatus($userInfo['token'],$login_id);
                    if ($rev == 2) return $login_id;
                }
                return NULL;
            }
        }
        
        $real_email = self::getEmailByCookie();
        $login_id   = self::getLoginIdByEmail($real_email);
        if (!empty($login_id)) {
            $userInfo  = OAuthUtils::getUserInfoFromMc($login_id);
            if (!empty($userInfo)) {
                $rev = self::chkSSOLoginStatus($userInfo['token'],$login_id);
                if ($rev == 2) return $login_id;
            }
        }
        return NULL;
    }/*}}}*/


    /**
     * @method-name : saveLoginInfo()
     * @parameter   : (string)$email - user's login email.
     * @parameter   : (string)$lang  - user's default lang.
     * @description : save the user's info when logined.
     * @return      : mixed
     * @author      : stephen.mo <stephen.mo@achievo.com>
     * @date        : Dec 8,2010
     */
    static public function saveLoginInfo($email,$lang='zh-hant-hk') {/*{{{*/
        $time = time();
        $lang = (!empty($lang)) ? self::chkLang($lang) : OAuthConfig::DEFAULT_SUPPORT_LANG;
        setcookie('mm_tvb_email',$email,OAuthModelConfig::MOBILE_LOGIN_INFO_EXPIRE_TIME+$time,"/",".tvb.com");
        setcookie('m_tvb_lang',$lang,OAuthModelConfig::MOBILE_LOGIN_INFO_EXPIRE_TIME+$time,"/",".tvb.com");
        return TRUE;
    }/*}}}*/
    
    /**
     * @method-name : delLoginInfo()
     * @parameter   : NULL
     * @description : delete login infos.
     * @return      : bool
     * @author      : stephen.mo <stephen.mo@achievo.com>
     * @date        : Jan 17,2011
     */
    static public function delLoginInfo() {/*{{{*/
        $now_time = time();
        $expiry_time = (empty($expiry_time)) ? OAuthConfig::SET_COOKIE_EXPIRE_TIME*60 : $expiry_time*60;
        //unset login infos.
        setcookie('mm_tvb_email','', $now_time - $expiry_time, "/", ".tvb.com");
        if (isset($_COOKIE['mm_tvb_email'])) unset($_COOKIE['mm_tvb_email']);
        return TRUE; 
    }/*}}}*/
    
    /**
     * @method-name : delUserMcInfo()
     * @parameter   : (string)$login_id - login id.
     * @description : clear user info from memcache.
     * @return      : bool
     * @author      : stephen.mo <stephen.mo@achievo.com>
     * @date        : Jan 18,2011
     */
    static public function delUserMcInfo($login_id) {/*{{{*/
        if (empty($login_id)) return FALSE;
        $ret = OAuthModel::getInstance()->delete(md5($login_id));
        return $ret;
    }/*}}}*/

    /**
     * @method-name : chkLang().
     * @parameter   : (string)$lang - the current lang.  
     * @description : check the current lang is or not support.
     * @return      : string
     * @author      : stephen.mo
     * @date        : 2010/09/13
     */
    static public function chkLang($lang) {/*{{{*/
        $default_supports = array('zh-hant-hk','zh-hans-hk','en-hk');
        if (!empty($lang) && in_array($lang,$default_supports)) {
            return $lang;
        }
        return $default_supports[0];
    }/*}}}*/

    /**
     * @method-name : redirectTo().
     * @parameter   : (string)$page - the page url.
     * @parameter   : (array)$params - params array list.
     * @return      : string
     * @author  : stephen.mo
     * @date    : 2010/09/13
     */
    static public function redirectTo($page=NULL,$params=array()) {/*{{{*/
        $paramstring = '';
        if (sizeof($params)) {
            foreach($params as $key => $val) {
                if (strpos('url',$key)) {
                    $paramstring .= "&{$key}=".urlencode($val);
                }
                else {
                    $paramstring .= '&'.$key.'='.$val;//"&{$key}={$val}";
                }
            }
        }
        if (strpos('lang',$page)===false && !in_array('m_lang',$params)) {
            $default_lang = '&lang='.self::getLang();
        }
        if ($page=='restart_url') {
            $page = OAuthConfig::OAuthDomainUrl().OAuthConfig::DEFAULT_CMODEL_URL.'?lang='.self::getLang();
        }
        
        //redirect to page.
        $call_back    = (isset($params['call_back'])) ? $params['call_back'] : (isset($params['oauth_callback']) ? $params['oauth_callback'] : NULL);
        $default_page = OAuthConfig::OAuthDomainUrl().OAuthConfig::DEFAULT_SHOW_MESSAGE_URL.'?act=ERROR'.$default_lang.
                        '&flag=error&errids='.json_encode(array(1029,1030)).'&call_back='.urlencode($call_back);
        $real_page    = (empty($page)) ? $default_page : $page.$paramstring;
        header("Location:$real_page");
        exit;
    }/*}}}*/

    /**
     * @method-name : getUser().
     * @parameter   : NULL
     * @return      : array 
     * @author  : stephen.mo
     * @date    : 2010/09/13
     */
    static public function getUserInfo() {/*{{{*/
        $userInfo = array();
        $userInfo['user']    = (isset($_COOKIE['m_tvb_user'])) ? $_COOKIE['m_tvb_user'] : NULL;
        $userInfo['pass']    = (isset($_COOKIE['m_tvb_pass'])) ? $_COOKIE['m_tvb_pass'] : NULL;
        $userInfo['remeber'] = (isset($_COOKIE['m_tvb_remeber'])) ? $_COOKIE['m_tvb_remeber'] : 0;
        $userInfo['imei']    = (isset($_COOKIE['m_tvb_imei'])) ? $_COOKIE['m_tvb_imei'] : NULL;
        $userInfo['from']    = (isset($_COOKIE['m_tvb_from'])) ? $_COOKIE['m_tvb_from'] : NULL;
        return $userInfo;
    }/*}}}*/

    /**
     * @method-name : setUserInfo()
     * @parameter   : (array)$userInfo
     * @description : set ptoken to cookie
     * @return : bool 
     * @author : stephen.mo
     * @date : 2010/09/10
     */
    static public function setUserInfo($userInfo,$expiry_time=NULL) {/*{{{*/
        $now_time = time();
        $expiry_time = (empty($expiry_time)) ? OAuthConfig::SET_COOKIE_EXPIRE_TIME*60 : $expiry_time*60;
        if (isset($userInfo['user'])) {
            setcookie('m_tvb_user',$userInfo['user'],$expiry_time+$now_time,"/",".tvb.com");
        }
        if (isset($userInfo['pass'])) {
            setcookie('m_tvb_pass',$userInfo['pass'],$expiry_time+$now_time,"/",".tvb.com");
        }
        if (isset($userInfo['remeber'])) {
            setcookie('m_tvb_remeber',$userInfo['remeber'],$expiry_time+$now_time,"/",".tvb.com");
        }
        if (isset($userInfo['phone_imei'])) {
            setcookie('m_tvb_imei',$userInfo['phone_imei'],$expiry_time+$now_time,"/",".tvb.com");
        }
        
        if (isset($userInfo['from'])) {
            setcookie('m_tvb_from',$userInfo['from'],$expiry_time+$now_time,"/",".tvb.com");
        }
        else {
            setcookie('m_tvb_from','',$now_time-$expiry_time,"/",".tvb.com");
            if (isset($_COOKIE['m_tvb_from'])) unset($_COOKIE['m_tvb_from']);
        }
        return true;
    }/*}}}*/

     /**
     * @method-name : delUserInfo()
     * @parameter   : NULL 
     * @description : delete user info from cookie
     * @return : bool 
     * @author : stephen.mo
     * @date : 2010/09/10
     */
    static public function delUserInfo($expiry_time=NULL) {/*{{{*/
        $now_time = time();
        $expiry_time = (empty($expiry_time)) ? OAuthConfig::SET_COOKIE_EXPIRE_TIME*60 : $expiry_time*60;
        setcookie('m_tvb_user','', $now_time - $expiry_time, "/", ".tvb.com");
        setcookie('m_tvb_pass','', $now_time - $expiry_time, "/", ".tvb.com");
        setcookie('m_tvb_remeber','', $now_time - $expiry_time, "/", ".tvb.com");
        setcookie('m_tvb_imei','',$now_time-$expiry_time,"/",".tvb.com");
        setcookie('m_tvb_from','',$now_time-$expiry_time,"/",".tvb.com");

        if (isset($_COOKIE['m_tvb_user'])) unset($_COOKIE['m_tvb_user']);
        if (isset($_COOKIE['m_tvb_pass'])) unset($_COOKIE['m_tvb_pass']);
        if (isset($_COOKIE['m_tvb_remeber']))unset($_COOKIE['m_tvb_remeber']);
        if (isset($_COOKIE['m_tvb_imei'])) unset($_COOKIE['m_tvb_imei']);
        if (isset($_COOKIE['m_tvb_from'])) unset($_COOKIE['m_tvb_from']);
        return true;
    }/*}}}*/
   

    /**
     * @method-name : getRequest().
     * @parameter   : NULL
     * @return      : array 
     * @description : get request vars from cookie.
     * @author  : stephen.mo
     * @date    : 2010/09/13
     */
    static public function getRequest() {/*{{{*/
        $params = array();
        $params['rand_code']      = (isset($_COOKIE['m_tvb_randcode'])) ? $_COOKIE['m_tvb_randcode'] : NULL;
        $params['request_token']  = (isset($_COOKIE['m_tvb_request'])) ? $_COOKIE['m_tvb_request'] : NULL;
        $params['request_secret'] = (isset($_COOKIE['m_tvb_secret'])) ? $_COOKIE['m_tvb_secret'] : NULL;
        return $params;
    }/*}}}*/

    /**
     * @method-name : setRequest()
     * @parameter   : (array)$vars
     * @description : set request params to cookie
     * @return : bool 
     * @author : stephen.mo
     * @date : 2010/09/10
     */
    static public function setRequest($vars,$expiry_time=NULL) {/*{{{*/
        $now_time = time();
        $expiry_time = (empty($expiry_time)) ? OAuthConfig::SET_COOKIE_EXPIRE_TIME*60 : $expiry_time*60;
        setcookie('m_tvb_randcode',$vars['rand_code'],$expiry_time+$now_time,"/",".tvb.com");
        setcookie('m_tvb_request',$vars['request_token'],$expiry_time+$now_time,"/",".tvb.com");
        setcookie('m_tvb_secret',$vars['request_secret'],$expiry_time+$now_time,"/",".tvb.com");
        return true;
    }/*}}}*/

    /**
     * @method-name : getPToken().
     * @parameter   : NULL
     * @return      : string
     * @author  : stephen.mo
     * @date    : 2010/09/13
     */
    static public function getPToken() {/*{{{*/
        $ptoken = (isset($_COOKIE['m_tvb_ptoken'])) ? $_COOKIE['m_tvb_ptoken'] : NULL;
        return $ptoken;
    }/*}}}*/

    /**
     * @method-name : setPToken()
     * @parameter   : (string)$ptoken
     * @description : set ptoken to cookie
     * @return : NULL
     * @author : stephen.mo
     * @date : 2010/09/10
     */
    static public function setPToken($ptoken) {/*{{{*/
        $now_time = time();
        setcookie('m_tvb_ptoken',$ptoken,OAuthConfig::SET_COOKIE_EXPIRE_TIME*60+$now_time,"/",".tvb.com");
    }/*}}}*/
    
    /**
     * @method-name : delPToken()
     * @description : delete ptoken from cookie
     * @return : NULL
     * @author : stephen.mo
     * @date : 2010/09/10
     */
    static public function delPToken() {/*{{{*/
        $now_time = time();
        setcookie('m_tvb_ptoken', '', $now_time - (OAuthConfig::SET_COOKIE_EXPIRE_TIME*60), "/", ".tvb.com");
        unset($_COOKIE['m_tvb_ptoken']);
    }/*}}}*/

    /**
     * @method-name : reGenPUKey()
     * @parameter   : (string)$ptoken
     * @parameter   : (string)$pukey
     * @description : re-create a new pukey. 
     * @return : NULL
     * @author : stephen.mo
     * @date : 2010/09/10
     */
    static public function reGenPUKey($pukey,$ptoken) {/*{{{*/
        $keyInfo = OAuthModel::getInstance()->reGenFormPUKey($pukey,$ptoken);
        $retFlag = (isset($keyInfo->retFlag)) ? $keyInfo->retFlag : 0;
        $info    = (isset($keyInfo->retFlag)) ? $keyInfo->info : NULL;
        $data    = (isset($keyInfo->data)) ? $keyInfo->data : array();
        $tmp_retry_url = OAuthConfig::OAuthDomainUrl().OAuthConfig::DEFAULT_CMODEL_URL;
        if (isset($_REQUEST['reback_url'])&&!empty($_REQUEST['reback_url'])) {
            $params['retry_url'] = urlencode($_REQUEST['reback_url']);
        }
        else {
            if (isset($_REQUEST['oauth_token'])) {
                $tmp_retry_url .= '?oauth_token='.$_REQUEST['oauth_token'];
            }
            if (isset($_REQUEST['login_id'])) {
                $tmp_retry_url .= '&login_id='.$_REQUEST['login_id'];
            }
            if (isset($_REQUEST['lang'])) {
                $tmp_retry_url .= '&lang='.$_REQUEST['lang'];
            }
            if (isset($_REQUEST['call_back'])) {
                $tmp_retry_url .= '&call_back='.urlencode($_REQUEST['call_back']);
            }
            $params['retry_url'] = $tmp_retry_url;
        }

        if (!$retFlag) {
            self::delPToken();
            if ($info == 'expire') {
                $error_ids = array(1030);
            }
            else {
                $error_ids = array(1029,1030);
            }
            $redirect_page = self::genericError($error_ids);
            //self::MsgDebugLog('xxxxx',$redirect_page);
            self::redirectTo($redirect_page,$params);
        }
        
        if (!isset($data->pukey) || !isset($data->ptoken)) {
            $redirect_page = self::genericError(array(1000));
            self::redirectTo($redirect_page,$params);
        }

        return $data->pukey;

    }/*}}}*/


    /**
     * @method-name : genericError()
     * @parameter   : (string)$error_txt
     * @parameter   : (array)$error_ids
     * @description : the generic error url. 
     * @return : NULL
     * @author : stephen.mo
     * @date : 2010/09/10
     */
    static public function genericError($error_ids=array(),$error_txt=NULL) {/*{{{*/
        $error_ids        = (empty($error_ids)) ? array(1029,1030) : $error_ids;
        $base_server_path = OAuthConfig::OAuthDomainUrl();
        $msgbox_url       = $base_server_path.OAuthConfig::DEFAULT_SHOW_MESSAGE_URL;
        $lang             = (isset($_REQUEST['lang']) && !empty($_REQUEST['lang'])) ? self::chkLang($_REQUEST['lang']) : self::getLang();
        $real_msgbox_url  = $msgbox_url.'?lang='.$lang.'&flag=error&act=ERROR&errids='.json_encode($error_ids);
        return $real_msgbox_url;
    }/*}}}*/

    /**
     * @method-name : getFormData()
     * @parameter   : (string)$pukey
     * @parameter   : (string)$ptoken
     * @description : get the form data from memcache. 
     * @return : object
     * @author : stephen.mo
     * @date : 2010/09/10
     */
    static public function getFormData($pukey,$ptoken) {/*{{{*/
        $ret = OAuthModel::getInstance()->getFormData($pukey,$ptoken);
        $tmpData = NULL;
        if ($ret->retFlag) {
            $tmpData = json_decode($ret->data);
        }
        $ret->data = $tmpData;
        return $ret;
    }/*}}}*/
    
    /**
     * @method-name : setFormData()
     * @parameter   : (string)$pukey
     * @parameter   : (string)$ptoken
     * @parameter   : (array) $fdata 
     * @description : set the data to memcache. 
     * @return : NULL
     * @author : stephen.mo
     * @date : 2010/09/10
     */
    static public function setFormData($pukey,$ptoken,$fdata) {/*{{{*/
        $ret = OAuthModel::getInstance()->setFormData($pukey,$ptoken,$fdata);
        return $ret;
    }/*}}}*/

    /**
     * @method-namd : get url's domain
     * @parameter   : (string)$url
     * @description : get domain from url.
     * @return : string
     * @author : stephen.mo
     * @date : 2010/09/16
     */
    static public function getDomainByUrl($url) {/*{{{*/
        preg_match("/^(http:\/\/)?([^\/]+)/i",
                    $url, $matches);
        $host = $matches[2];
        preg_match("/[^\.\/]+\.[^\.\/]+\.[^\.\/]+$/", $host, $matches);
        return $matches[0]; 
    }/*}}}*/

    /**
     * @method-name : chkUserState().
     * @parameter   : 
     * @description : check users' state.
     * @return : bool.
     * @author : stephen.mo
     * @date : 2010/09/24
     */
    static public function chkUserState() {/*{{{*/
        $requestInfo = self::getRequest();
        $userInfo    = self::getUserInfo();
        if (empty($requestInfo) || empty($userInfo) || !isset($requestInfo['request_token']) || !isset($userInfo['user'])) return FALSE;
        $ret = OAuthModel::getInstance()->chkUserIsLogined($requestInfo['request_token'],$userInfo['user']);
        return $ret;
    }/*}}}*/

    /**
     * @method-name : saveUserInfo()
     * @parameter   : (array)$params.
     * @description : save user info to memcache.
     * @return : bool
     * @date : 2010/09/17
     */
    static public function saveUserInfoToMc($params,$expiry_time=NULL) {/*{{{*/
        $ret = OAuthModel::getInstance()->saveUserInfoToMc($params,$expiry_time);
        return $ret;
    }/*}}}*/
    
    /**
     * @method-name : chkUserPassword().
     * @parameter   : (string)$username - users' login id.
     * @parameter   : (string)$password - users' password.
     * @description : check the username and password is correctly.
     * @return : bool.
     * @author : stephen.mo
     * @date : 2010/09/24
     */
    static public function chkUserPassword($username,$password) {/*{{{*/
        $ret = OAuthModel::getInstance()->chkUserPassword($username,$password);
        return $ret;
    }/*}}}*/

    /**
     * @method-name : checkUserState().
     * @parameter   : (string)$login_id - member's login id;
     * $parameter   : (strint)$phone_imei - phone imei string.
     * @description : check user is logined?
     * @return : mixed
     * @author : stephen.mo
     * @date : 2010/09/24
     */
    static public function checkUserState($login_id=NULL,$phone_imei=NULL) {/*{{{*/
        if (empty($login_id)) {
            $userInfo  = self::getUserInfo();
            $login_id  = $userInfo['user'];
        }
        $rev = OAuthModel::getInstance()->chkUserIsLogined($login_id,$phone_imei);
        return $rev;
    }/*}}}*/


    /**
     * @method-name : getConsumerKeyByToken().
     * @parameter   : (string)$request_token - the request token string.
     * @description : get the consumer key list by request token string,when you need.
     * @return : string.
     * @author : stephen.mo
     * @date :2010/09/24
     */
    static public function getConsumerKeyByToken($request_token,$expiry_time=NULL) {/*{{{*/
        if (empty($request_token)) return NULL;
        $expiry_time = (empty($expiry_time)) ? OAuthModelConfig::MEMCACHE_EXPIRED_TIME*60 : $expiry_time*60;
        $ret = OAuthModel::getInstance()->getConsumerKeyByToken($request_token,$expiry_time);
        return $ret;
    }/*}}}*/

    /**
     * @method-name : authorizedRequestToken().
     * @parameter   : (array)$requests - the request vars.
     * @description : authorize request token and return it.
     * @return : mixed.
     * @author : stephen.mo
     * @date : 2010/09/24
     */
    static public function authorizedRequestToken($request) {/*{{{*/
        $request['expiry_time'] = OAuthModelConfig::SAVE_MEMBER_INFO_ETIME;
        $rev = OAuthModel::getInstance()->authorizedRequestToken($request);
        return $rev;
    }/*}}}*/

    /**
     * @method-name : getLoginIdByEmail().
     * @parameter   : (string)$email
     * @description : get user's login id by email.
     * @return : string
     * @author : stephen.mo
     * @date : 2010/09/17
     */
    static public function getLoginIdByEmail($email) {/*{{{*/
        if (empty($email)) return NULL;
        $ret = OAuthModel::getInstance()->getLoginIdByEmail($email);
        if ($ret->retFlag==1) {
            return $ret->result->login_id;
        }
        return NULL;
    }/*}}}*/

    /**
     * @method-name : checkVerifiable().
     * @parameter   : (string)$consumer_key
     * @description : check this consumer key is or not need verify.
     * @return : bool
     * @author : stephen.mo
     * @date : 2010/09/27
     */
    static public function checkVerifiable($consumer_key) {/*{{{*/
        if (empty($consumer_key)) return TRUE;
        $ret = OAuthModel::getInstance()->checkVerifiable($consumer_key);
        return $ret;
    }/*}}}*/

    /**
     * @method-name : checkTokenAuthorized().
     * @parameter   : (string)$verify_code
     * @description : check token is or not authorized by verify code.
     * @return : string
     * @author : stephen.mo
     * @date : 2010/09/27
     */
    static public function checkTokenAuthorized($verify_code) {/*{{{*/
        if (empty($verify_code)) return NULL;
        $ret = OAuthModel::getInstance()->checkTokenAuthorized($verify_code);
        return $ret;
    }/*}}}*/

    /**
     * @method-name : updateAuthorized().
     * @parameter   : (string)$access_token.
     * @parameter   : (string)$verify_code.
     * @parameter   : (string)$request_token.
     * @description : using these string update the authorized token.
     * @return : bool
     * @author : stephen.mo
     * @date : 2010/09/27
     */
    static public function updateAuthorized($access_token_string,$verify_code,$request_token) {/*{{{*/
        if (empty($access_token_string) || empty($request_token)) return FALSE;
        $ret = OAuthModel::getInstance()->updateAuthorized($access_token_string,$verify_code,$request_token);
        return $ret;
    }/*}}}*/

    /**
     * @method-name : loginForMobile() 
     * @parameter   : (string)$login_id.
     * @parameter   : (strint)$password.
     * @parameter   : (strint)$map_from.
     * @description : using login_id/email login into MS.
     * @return      : mixed.
     * @author      : stephen.mo
     * @date        : Oct 12,2010
     */
    static public function loginForMobile($login_id,$password,$map_from=NULL,$need_check=FALSE) {/*{{{*/
        if (empty($login_id)) return FALSE;
        if (empty($password)) return FALSE;
        $params['login_id'] = $login_id;
        $params['password'] = $password;

        //need to check user has valid subscirption. 
        if ($need_check) {
            //$tmp_login_id = self::getLoginIdByEmail($login_id);  
            //$rev = self::chkIfUserCanBuyPlan($tmp_login_id);
            $rev = self::chkIfUserCanBuyPlan($login_id);
            if (!$rev) return -1;
        }
        if (!empty($map_from) && ($map_from==OAuthModelConfig::PCCW_OAUTH_FROM_TYPE)) {
            $params['map_from_type'] = $map_from;
        }
        $ret = OAuthModel::getInstance()->loginForMobile($params);
        if ($ret->retFlag != 1) {
            return FALSE;
        }
        return $ret;
    }/*}}}*/

    /**
     * @method-name : chkSSOLoginStatus()
     * @parameter   : (strint)$token - the logined token of member
     * @parameter   : (strint)$login_id .
     * @description : check user's status of login.
     * @return      : int
     * @author      : stephen.mo
     * @date        : Oct 12,2010
     */
    static public function chkSSOLoginStatus($token,$login_id) {/*{{{*/
        if (empty($token)) return FALSE;
        if (empty($login_id)) return FALSE;
        $params['token']    = $token;
        $params['login_id'] = $login_id;
        $ret = OAuthModel::getInstance()->chkSSOLoginStatus($params);
        return $ret;
    }/*}}}*/


    /**
     * @method-name : getLoginIdByUserId()
     * @parameter   : (strint)$user_id - pccw's user id
     * @description : get membership's login_id by pccw's user id.
     * @return      : mixed
     * @author      : stephen.mo
     * @date        : Oct 20,2010
     */
    static public function getLoginIdByUserId($user_id) {/*{{{*/
        if (empty($user_id)) return FALSE;
        $oauthModel = OAuthModel::getInstance();
	if(is_object($oauthModel)) $ret= $oauthModel->getLoginIdByUserId($user_id);
        if (empty($ret)) return FALSE;
        return $ret;
    }/*}}}*/


    /**
     * @method-name : getThirdPartiesList().
     * @parameter   : NULL
     * @description : get support third parties list
     * @return      : array
     * @author      : stephen.mo
     * @date        : Oct 20,2010
     */
    static public function getThirdPartiesList() {/*{{{*/
        $rev    = array();
        $config = ConfigReaderFactory::getInstance()->getConfigReader(OAuthModelConfig::THIRD_PARTIES_LIST)->getConfig();
        foreach($config->item as $val) {
            if (isset($val->display) && $val->display==1) {
                $rev[] = (array)$val;
            }
        }
        return $rev;

    }/*}}}*/

    
    /**
     * @method-name : MsgDebugLog().
     * @parameter   : (strint)$name - function name.
     * @parameter   : (strint)$info
     * @return      : NULL
     * @author      : stephen.mo
     * @date        : Oct 28,2010
     */
    static public function MsgDebugLog($name,$info) {/*{{{*/
        if (!OAuthModelConfig::DEFAULT_DEBUG_SWITCH) return FALSE;
        $log_path = OAuthModelConfig::OAUTH_DEBUG_LOG_PATH;
        $now_time = date('Ymd');
        $file_name = $log_path.$now_time.'.log';
        $hand = fopen($file_name,'a+');
        $content = '['.date('Y-m-d H:i:s').']   '.$name.'   '.$info."\n";
        fwrite($hand,$content);
        fclose($hand);

    }/*}}}*/

    /**
     * @method-name : DecryptPccwString().
     * @parameter   : (string)$token
     * @description : using a publickey to decrypt encrypt string,and get a real token string.
     *                <NOW>
     *                  <TIMESTAMP>20101101171302</TIMESTAMP>
     *                  <NOWID>xxxx-xx-xxxx-xx-xxxx</NOWID>
     *                  <PLANID>tbdplanid</PLANID>
     *                  <IP>123.123.123.123</IP>
     *                  <VIDEOURL>tbdvideourl</VIDEOURL>
     *                </NOW>
     * @return      : XML string.
     * @author      : stephen.mo
     * @date        : Nov 2,2010
     */
    static public function DecryptPccwString($token) {/*{{{*/
        if (empty($token)) return FALSE;
        $jar_file = OAuthModelConfig::OAUTH_PCCW_JAR_PATH.'pccw_access_token_decrypt/MediaCryptoDecrypt.jar';
        $pub_key  = OAuthModelConfig::OAUTH_PCCW_JAR_PATH.'pccw_access_token_decrypt/tvbuatmobilersa4096public.key';
        if (!is_file($jar_file)) return FALSE;
        if (!is_file($pub_key)) return FALSE;
        $command = "java -classpath ".$jar_file." com.netvigator.media.crypto.decrypt.sampleDecrypt RSA ".$pub_key." ".$token;
        @exec($command,$output,$return);
        if (is_array($output) && count($output)==4) {
            if (empty($output[3])) return FALSE;
            $plit = str_ireplace("Plain Text: ", "", $output[3]);
            $plan_text = trim($plit);
            if ( !empty($plan_text)) {
                $token_code = trim($plan_text);
                $obj = simplexml_load_string($token_code, 'SimpleXMLElement', LIBXML_NOCDATA);
                if (empty($obj->MASKEDNPID)) return FALSE;
                return $obj;
            }
            return FALSE;
        }
        return FALSE;


    }/*}}}*/


    /**
     * @method-name : chkIsExistsThirdPartyLogin()
     * @parameter   : NULL
     * @description : check this version is or not to show the third-party login link.
     * @return      : bool
     * @author      : stephen.mo
     * @date        : Nov 8,2010
     */
    static public function chkIsExistsThirdPartyLogin() {/*{{{*/
        $third_party_conf = OAuthModelConfig::THIRD_PARTIES_LIST;
        $third_party_listpage = '/data/httpd/htdocs/'.OAuthConfig::BASE_DOMAIN.OAuthConfig::DEFAULT_THIRD_PARTIES_URL;
        if (is_file($third_party_conf) && is_file($third_party_listpage)) {
            $items = self::getThirdPartiesList();
            if (count($items) > 0) {
                return TRUE;
            }
        }
        return FALSE;
    }/*}}}*/
    
    /**
     * @method-name : getSuffixOfFile()
     * @parameter   : (string)$filename.
     * @description : get file's suffix string.
     * @return      : string
     * @author      : stephen.mo
     * @date        : Nov 8,2010
     */
    static public function getSuffixOfFile($filename) {/*{{{*/
        if (empty($filename)) return NULL;
        $suffix = end(explode('.',$filename));
        return strtolower($suffix);
    }/*}}}*/

    /**
     * @method-name : getPrefixOfFile()
     * @parameter   : (string)$filename.
     * @description : get the filenames' prefix string.
     *                the file's prefix must be same as website's sub directory.
     *                eg:3.com_payment.xml = >htdocs/domain/3.com/
     * @return      : string.
     * @author      : stephen.mo
     * @date        : Nov 9,2010
     */
    static public function getPrefixOfFile($filename) {/*{{{*/
        if (empty($filename)) return NULL;
        $prefix = current(explode('_',$filename));
        return strtolower($prefix);
    }/*}}}*/


    /**
     * @mehtod-name : getFilesByPath()
     * @parameter   : (string)$path - directory's path.
     * @description : get the $path's file name.not include dir.
     * @return      : array
     * @author      : stephen.mo
     * @date        : Nov 8,2010
     */
    static public function getFilesByPath($real_path) {/*{{{*/
        if (empty($real_path) || !is_dir($real_path)) return NULL;
        $supply_suffix = OAuthModelConfig::$supply_suffix_name;
        $command       = 'ls '.$real_path;
        $rev    = @exec($command,$output,$return);
        $result = array();
        if (empty($output)) return $result;
        foreach($output as $list) {
            $suffix_tmp = self::getSuffixOfFile($list);  //get suffix string.
            $prefix_tmp = self::getPrefixOfFile($list);  //get prefix string.
            if (!in_array($suffix_tmp,$supply_suffix)) continue;
            $real_file = $real_path.$list;
            $config    = ConfigReaderFactory::getInstance()->getConfigReader($real_file)->getConfig();
            if (empty($config)) continue;
            foreach($config->item as $root) {
                if (empty($root)) continue;
                if ($root->display != 1) continue;
                $tmp_order = (string)$root->order;
                if (!isset($result[$tmp_order])) $result[$tmp_order] = array();
                $result[$tmp_order] = array('name'=>(string)$root->name,
                                            'order'=>(string)$root->order,
                                            'title'=>(string)$root->title,
                                            'rank'=>(string)$root->allow_guest,
                                            'prefix'=>$prefix_tmp,
                                            'description'=>(array)$root->description,
                                       );
            }
        }

        //sort the array by the key.
        ksort($result,SORT_NUMERIC);  
        return $result;
    }/*}}}*/


    /**
     * @method-name : getModelOfPayment()
     * @parameter   : NULL
     * @description : get all the model of payment lists.
     * @return      : mixed
     * @author      : stephen.mo
     * @date        : Nov 8,2010
     */
    static public function getModelOfPayment() {/*{{{*/
        $base_path = OAuthModelConfig::OAUTH_THIRD_PAYMENT_CONF_PATH;
        $payment_vars = self::getFilesByPath($base_path);
        return $payment_vars;    
    }/*}}}*/
    
    /**
     * @method-name : getPaymentConfDetail()
     * @parameter   : (string)$filepath
     * @description : get xml config detail node content by filepath.
     * @return      : mixed
     * @author      : stephen.mo
     * @date        : Nov 9,2010
     */
    static public function getPaymentConfDetail($filepath) {/*{{{*/
        $ret = array();
        $base_path = OAuthModelConfig::OAUTH_THIRD_PAYMENT_CONF_PATH;
        $file_name = $base_path.$filepath.'_payment.xml';
        if (is_file($file_name)) {
            $config = ConfigReaderFactory::getInstance()->getConfigReader($file_name)->getConfig();
            if (empty($config)) return NULL;
            foreach($config->detail as $root) {
                if (empty($root)) return NULL;
                switch($filepath) {
                    case OAuthModelConfig::DEFAULT_GATEWAY_OF_H3G:
                        $ret = array('get_msisdn_url'=>(string)$root->get_msisdn_url,'forward_page_url'=>(string)$root->forward_page_url,'shop_url'=>(string)$root->shop_url,);
                        break;
                    case OAuthModelConfig::DEFAULT_GATEWAY_OF_CSL:
                        $ret = array('home_page'=>(string)$root->home_page,'landing_page'=>(array)$root->landing_page,);
                        break;
                }
            }
        }
        return $ret;
    }/*}}}*/

    
    /**
     * @method-name : getNetworkType()
     * @parameter   : NULL
     * @description : get the mobile's network's type
     * @return      : string
     * @author      : stephen.mo
     * @date        : Nov 9,2010
     */
    static public function getNetworkType() {/*{{{*/
        $type = array('WIFI','3G');
        return $type[0];

    }/*}}}*/

    /**
     * @method-name : get3MsisdnId()
     * @parameter   : (string)$login_id 
     * @description : get a msisdn string by login id .
     * @return      : string
     * @author      : stephen.mo
     * @date        : Nov 9,2010
     */
    static public function get3MsisdnId($login_id) {/*{{{*/
        if (empty($login_id)) return NULL;
        $userInfo = self::getUserInfoFromMc($login_id);
        $result   = (isset($userInfo['msisdn_id'])) ? $userInfo['msisdn_id'] : NULL;
        return $result;
    }/*}}}*/
    

    /**
     * @method-name : chkSubscribedByMsisdn()
     * @parameter   : (strint)$msisdn_string.
     * @description : The 3.com's msisdn flag string.
     * @return      : bool
     * @author      : stephen.mo
     * @date        : Nov 10,2010
     */
    static public function chkSubscribedByMsisdn($msisdn_string) {/*{{{*/
        return false;
    }/*}}}*/
    
    /**
     * @method-name : chkH3gUserStatus().
     * @parameter   : (string)$login_id - tvb's login id.
     * @description : check a 3.com's user have subscripted or not?
     * @return      : bool
     * @author      : stephen.mo
     * @date        : Nov 11,2010
     */
    static public function chkH3gUserStatus($login_id) {/*{{{*/
        $params = array();
        $params['login_id'] = $login_id;
        $rev = OAuthModel::getInstance()->chkH3gUserStatus($params);
        return (int)$rev;
    }/*}}}*/
    
    /**
     * @method-name : getTvbAuthByLoginId()
     * @parameter   : (string)$login_id.
     * @description : get a encrypt tvbauth by login id.
     * @return      : string
     * @author      : stephen.mo
     * @date        : Nov 11,2010
     */
    static public function getTvbAuthByLoginId($login_id) {/*{{{*/
        if (empty($login_id)) return NULL;
        $params = array();
        $params['source'] = $login_id;
        $rev = OAuthModel::getInstance()->getTvbAuthByLoginId($params);
        return $rev;
    }/*}}}*/



    /**
     * @method-name : h3gPaymentSuccBack().
     * @parameter   : (string)$tvbauth - the tvb's login id. (encrypt)
     * @parameter   : (string)$msisdn  - the h3g's unqiue string.
     * $parameter   : (string)$network - 3G|2G|WIFI
     * @description : the succ back to do.
     * @return      : bool
     * @author      : stephen.mo
     * @date        : Nov 11,2010
     */
    static public function h3gPaymentSuccBack($tvbauth,$msisdn,$network=NULL) {/*{{{*/
        if (empty($tvbauth) || empty($msisdn)) return FALSE;
        $params = array();
        $params['tvbauth'] = str_replace(' ','+',$tvbauth);
        $params['msisdn']  = $msisdn;
        $params['network'] = $network;
        $rev = OAuthModel::getInstance()->h3gPaymentSuccessBack($params);
        return $rev;
    }/*}}}*/


    /**
     * @method-name : getCurrentMappingErrCode()
     * @parameter   : mixed
     * @description : return the current code by $error_id
     * @return      : array
     * @author      : stephen.mo
     * @date        : Nov 11,2010
     */
    static public function getCurrentMappingErrCode($error_id) {/*{{{*/
        return array(1000);
    }/*}}}*/
    
    /**
     * @method-name : forgetPassword()
     * @parameter   : (string)$email
     * @description : send a email and find your password.
     * @return      : bool
     * @author      : stephen.mo <stephen.mo@achievo.com>
     * @date        : Dec 8,2010
     */
    static public function forgetPassword($email) {/*{{{*/
        if (empty($email)) return FALSE;
        $params = array();
        $params['email'] = $email;
        $rev = OAuthModel::getInstance()->forgetPassword($params);
        return $rev;
    }/*}}}*/

    /**
     * @method-name : saveAccessTokenToMc()
     * @parameter   : (string)$access_token.
     * @description : save this token to mc with login id.
     * @return      : NULL;
     * @author      : stephen.mo <stephen.mo@achievo.com>
     * @date        : Dec 15,2010
     */
    static public function saveAccessTokenToMc($access_token) {/*{{{*/
        if (strpos($access_token,'&')) {
            parse_str($access_token,$tmp_access);
            $access_token = $tmp_access['oauth_token'];
        }
        $login_id = OAuthModel::getInstance()->getLoginIdByToken($access_token);
        if (empty($login_id)) return FALSE;
        $login_id = md5($login_id);
        $rev = OAuthModel::getInstance()->get($login_id);
        if (empty($rev)) return FALSE;
        $rev['access_token'] = $access_token;
        self::saveUserInfoToMc($rev,OAuthModelConfig::SAVE_MEMBER_INFO_ETIME);
        return TRUE;
    }/*}}}*/
    
    /**
     * @method-name : getUserInfoFromMc()
     * @parameter   : (string)$login_id. or member_id ,if member_id is exists.
     * @description : get user's info by login_id.
     * @return      : array
     * @author      : stephen.mo <stephen.mo@achievo.com>
     * @date        : Dec 15,2010
     */
    static public function getUserInfoFromMc($login_id) {/*{{{*/
        if (empty($login_id)) return FALSE;
        $key = md5($login_id);
        $rev = OAuthModel::getInstance()->get($key);
        if (empty($rev)) return FALSE;
        return $rev;
    }/*}}}*/

    /**
     * @method-name : getH3GMsisdnForWifi()
     * @parameter   : (string)$encode_string - the msisdn encypt string.
     * @description : decypt a string for msisdn.
     * @return      : string
     * @author      : stephen.mo <stephen.mo@achievo.com>
     * @date        : Dec 16,2010
     */
    static public function getH3GMsisdnForWifi($encode_string) {/*{{{*/
        if (empty($encode_string)) return NULL;
        $rev = OAuthModel::getInstance()->getH3GMsisdnForWifi($encode_string);
        return $rev;
    }/*}}}*/
    
    /**
     * @method-name : buyH3GPlanForWifi()
     * @parameter   : (string)$msisdn - the user's msisdn string.
     * @parameter   : (string)$login_id - the tvb's login id.
     * @description : buy a plan with WIFI network user.
     * @return      : bool
     * @author      : stephen.mo <stephen.mo@achievo.com>
     * @date        : Dec 16,2010
     */
    static public function buyH3GPlanForWifi($msisdn,$login_id) {/*{{{*/
        if (empty($msisdn) || empty($login_id)) return FALSE;
        $params = array();
        $params['msisdn'] = $msisdn;
        $rev = OAuthModel::getInstance()->buyH3GPlanForeifi($params);
        return $rev;
    }/*}}}*/

    /**
     * @method-name : toMessageUrl()
     * @parameter   : (string)$url - main url for message.
     * @parameter   : (string)$action - the action for message.
     * @parameter   : (string)$flag - message tags.
     * @parameter   : (string)$lang - language.
     * @parameter   : (array)$err_codes.
     * @parameter   : (array)$others - the others params
     * @description : generate a urls with error codes.
     * @return      : string
     * @author      : stephen.mo <stephen.mo@achievo.com>
     * @date        : Dec 17,2010
     */
    static public function toMessageUrl($url,$action,$flag,$lang,$err_codes=NULL,$others=NULL) {/*{{{*/
        $tmp_params = NULL;
        if (!empty($others)) {
            foreach((array)$others as $key=>$val) {
                $tmp_params .= '&'.$key.'='.$val;
            }
        }
        $err_codes  = (!empty($err_codes)) ? $err_codes : array(1000);
        $errids     = '&errids='.json_encode($err_codes);
        $msgbox_url = $url.'?act='.$action.'&flag='.$flag.'&lang='.$lang.$errids.$tmp_params;
        //return $msgbox_url;
        self::redirectTo($msgbox_url);
        return TRUE;
    }/*}}}*/
    
    /**
     * @method-name : verifyAccessToken()
     * @parameter   : (string)$access_token - 
     * @description : verify a access token.
     * @return      : mxied.
     * @author      : stephen.mo <stephen.mo@achievo.com>
     * @date        : Dec 17,2010
     */
    static public function verifyAccessToken($access_token) {/*{{{*/
        if (empty($access_token)) return FALSE;
        $rev = OAuthModel::getInstance()->verifyAccessToken($access_token);
        return $rev;
    }/*}}}*/
    
    /**
     * @method-name : chkIfUserCanBuyPlan()
     * @parameter   : (string)$login_id - member's login id.
     * @description : check a member can or not buy a plan.
     * @return      : bool
     * @author      : stephen.mo <stephen.mo@achievo.com>
     * @date        : Dec 17,2010
     */
    static public function chkIfUserCanBuyPlan($login_id) {/*{{{*/
        if (empty($login_id)) return FALSE;
        $rev = OAuthModel::getInstance()->chkIfUserCanBuyPlan($login_id);
        return $rev;
    }/*}}}*/

    /**
     * @method-name : genFormPUKey()
     * @parameter   : NULL
     * @description : gen a PUKey from mc.
     * @return      : mixed
     * @author      : stephen.mo <stephen.mo@achievo.com>
     * @date        : Dec 17,2010
     */
    static public function genFormPUKey() {/*{{{*/
        $rev = OAuthModel::getInstance()->genFormPUKey();
        return $rev;
    }/*}}}*/

    /**
     * @method-name : getPackageListByModel()
     * @parameter   : (string)$lang - language
     * @parameter   : (string)$model - default is 'TVB'
     * @description : get the support package list .
     * @return      : mixed
     * @author      : stephen.mo <stephen.mo@achievo.com>
     * @date        : Dec 17,2010
     */
    static public function getPackageListByModel($lang,$model='TVB') {/*{{{*/
        $lang = (empty($lang)) ? OAuthConfig::DEFAULT_SUPPORT_LANG : self::chkLang($lang);
        $rev  = OAuthModel::getInstance()->getPackageListByModel($lang,$model);
        return $rev;
    }/*}}}*/
    
    /**
     * @method-name : getPkgInfo()
     * @parameter   : (int)$pkg_id - package plan's id.
     * @parameter   : (int)$pkg_version - package plan's version.
     * @parameter   : (string)$lang - language.
     * @description : get pkg info by pkg_id & pkg_version.
     * @return      : object
     * @author      : stephen.mo <stephen.mo@achievo.com>
     * @date        : Dec 17,2010
     */
    static public function getPkgInfo($pkg_id,$pkg_version,$lang) {/*{{{*/
        $lang = (empty($lang)) ? OAuthConfig::DEFAULT_SUPPORT_LANG : OAuthUtils::chkLang($lang);
        $rev  = OAuthModel::getInstance()->getPkgInfo($pkg_id,$pkg_version,$lang);
        return $rev;
    }/*}}}*/
    
    /**
     * @method-name : getUserInfoByLoginId()
     * @parameter   : (string)$login_id.
     * @description : get user infos by login_id
     * @return      : mixed
     * @author      : stephen.mo <stephen.mo@achievo.com>
     * @date        : Dec 17,2010
     */
    static public function getUserInfoByLoginId($login_id) {/*{{{*/
        if (empty($login_id)) return NULL;
        $rev = OAuthModel::getInstance()->getUserInfoByLoginId($login_id);
        return $rev;
    }/*}}}*/
    
    /**
     * @method-name : logoutForMobile()
     * @parameter   : (string)$login_id - member's login_id
     * @parameter   : (string)$token    - mc's token string.
     * @description : logout a member.
     * @return      : bool
     * @author      : stephen.mo <stephen.mo@achievo.com>
     * @date        : Jan 17,2011
     */
    static public function logoutFormMobile($login_id,$token) {/*{{{*/
        //clear cookie by the user.
        $ret    = self::delLoginInfo();
        $ret    = (!empty($login_id)) ? self::delUserMcInfo($login_id) : TRUE;
        //need to clear MC and MS cache?
        $params = array();
        $params['login_id'] = $login_id;
        $params['token']    = $token;
        $ret = OAuthModel::getInstance()->logoutForMobile($params);
        return $ret;
    }/*}}}*/

    /**
     * @method-name : chkIpRange()
     * @parameter   : (string)$ip_address - the mobile's ip address.
     * $parameter   : (string)$gate_way - the gate way of third payment.
     * @description : check the mobile's ip range.
     * @return      : bool
     * @author      : stephen.mo <stephen.mo@achievo.com>
     * @date        : Mar 3,2011
     */
    static public function chkIpRange($gate_way,$ip_address) {/*{{{*/
        $ret = array();
        if (empty($ip_address)) return -1;
        $base_path = OAuthModelConfig::OAUTH_THIRD_PAYMENT_CONF_PATH;
        $file_name = $base_path.$gate_way.'_payment.xml';
        if (is_file($file_name)) {
            $config = ConfigReaderFactory::getInstance()->getConfigReader($file_name)->getConfig();
            if (empty($config)) return -1;
            $tag = FALSE;
            foreach($config->ip_range->regx_ip as $root) {
                $root = (array)$root;
                if (empty($root)) continue;
                $condition  = (string)$root['@attributes']['condition'];
                $relation  = isset($root['@attributes']['relation']) ? (string)$root['@attributes']['relation'] : NULL;
                switch($condition) {
                    case 'BETWEEN':
                        $flag = FALSE;
                        $root_expr = (array)$root['expression'];
                        foreach($root_expr as $expression) {
                            if ((empty($relation) || $relation=='OR') && preg_match($expression,$ip_address)) $flag = TRUE;
                            if (($relation == 'AND') && !preg_match($expression,$ip_address)) $flag = FALSE;
                        }
                        if ($flag) return $flag;
                        unset($expression);
                        break;
                    case 'EQUAL':
                        $flag = FALSE;
                        $root_expr = (array)$root['expression']; 
                        foreach($root_expr as $expression) {
                            if ((empty($relation) || $relation=='OR') && ($expression == $ip_address)) $flag = TRUE;
                            if (($relation == 'AND') && ($expression != $ip_address)) $flag = FALSE;
                        }
                        if ($flag) return $flag;
                        unset($expression);
                        break;
                }
                //flag of xml config.
                $tag = TRUE;
            }
            if (!$tag) return -1;
            return $flag;
        }
        return -1;

    }/*}}}*/

    /**
     * @method-name : decryptMsisdn()
     * @parameter   : (string)$msisdn - the msisdn string.
     * @description : decrypt a string of msisdn.
     * @return      : array
     * @author      : stephen.mo <stephen.mo@achievo.com>
     * @date        : Mar 4,2011
     */
    static public function decryptMsisdn($msisdn) {/*{{{*/
        $ret = array();
        if (empty($msisdn)) return $ret;
        $msisdns = explode('|',base64_decode($msisdn));
        $ret['msisdn_str']  = (!empty($msisdns) && isset($msisdns[0])) ? $msisdns[0] : NULL;
        $ret['msisdn_time'] = (!empty($msisdns) && isset($msisdns[1])) ? $msisdns[1] : 0;
        return $ret;
    }/*}}}*/

    /**
     * @method-name : genCrumbString().
     * @parameter   : (tinyint)$format - the encryption string.
     * @description : with $format generate a encryption string.
     * @return      : string
     * @author      : stephen.mo <stephen.mo@achievo.com>
     * @date        : Mar 7,2011
     */
    static public function genCrumbString($params,$format=1) {/*{{{*/
        if (empty($params)) return NULL;
        $expire_time = (isset($params['exT'])) ? $params['exT'] : NULL;
        $random_num  = (isset($params['randN'])) ? $params['randN'] : NULL;
        $client_ip   = (isset($params['clientIp'])) ? $params['clientIp'] : NULL;
        $crumb_key   = OAuthModelConfig::THIRD_PAYMENT_CRUMB_KEY;

        switch($format) {
            case 1:
                $return = sha1($client_ip.$random_num.$expire_time.$crumb_key);
                break;
            case 2:
                $login_id = (isset($params['loginId'])) ? $params['loginId'] : NULL;
                $return = sha1($login_id.$random_num.$client_ip.$crumb_key.$expire_time);
                break;
            default:
                $return = NULL;
        }

        return $return;

    }/*}}}*/

    
    /**
     * @method-name : cslPaymentSuccessBack()
     * @paramter    : (string)$tvbauth - the auth string of tvb's member.
     * @parameter   : (string)$msisdn - msisdn id string.
     * @description : when success callback to do it.
     * @return      : bool
     * @author      : stephen.mo <stephen.mo@achievo.com>
     * @date        : Mar 8,2011
     */
    static public function cslPaymentSuccessBack($tvbauth,$token,$network_type) {/*{{{*/
        if (empty($tvbauth) || empty($token)) return FALSE;
        $params = array();
        $params['tvbauth'] = str_replace(' ','+',$tvbauth);                    
        $params['token']  = $token;
        $params['network'] = $network_type;
        $rev = OAuthModel::getInstance()->cslPaymentSuccessBack($params);
        return $rev;
    }/*}}}*/
    
    /**
     * @method-name : chkCslUserStatus().
     * @parameter   : (string)$login_id - the logind id for tvb member.
     * @description : chk tvb member's local payment plan status.
     * @return      : bool
     * @author      : stephen.mo <stephen.mo@achievo.com>
     * @date        : Mar 8,2011
     */
    static public function chkCslUserStatus($login_id) {/*{{{*/
        if (empty($login_id)) return FALSE;
        $params = array('login_id'=>$login_id);
        $rev = OAuthModel::getInstance()->chkCslUserStatus($params);
        return $rev;
    }/*}}}*/

    /**
     * @method-name : chkMemberLocalStatus().
     * @parameter   : (string)$login_id - the member's login_id.
     * @parameter   : (string)$gate_way - the payment gate way.
     * @description : As the diffrent gate-way using diffrent API.
     * @return      : bool
     * @author      : stephen.mo <stephen.mo@achievo.com>
     * @date        : Mar 8,2011
     */
    static public function chkMemberLocalStatus($login_id,$gate_way=NULL) {/*{{{*/
        $gate_way = (empty($gate_way)) ? OAuthModelConfig::DEFAULT_GATEWAY_OF_H3G : $gate_way;
        if (empty($login_id)) return FALSE;
        switch($gate_way) {
            case OAuthModelConfig::DEFAULT_GATEWAY_OF_H3G:
                $ret = self::chkH3gUserStatus($login_id);
                break;
            case OAuthModelConfig::DEFAULT_GATEWAY_OF_CSL:
                $ret = self::chkCslUserStatus($login_id);
                break;
            case OAuthModelConfig::DEFAULT_GATEWAY_OF_PCCW:
                return FALSE;
                break;
            case OAuthModelConfig::DEFAULT_GATEWAY_OF_SMARTONE:
                return FALSE;
                break;
            default:
                return FALSE;
        }
        return $ret;
    
    }/*}}}*/
    
    /**
     * @method-name : getAuthKeyVal()
     * @parameter   : (int)$node - node id.
     * @description : get the auth key setting.
     * @return      : array
     * @author      : stephen.mo <stephen.mo@achievo.com>
     * @date        : Mar 9,2011
     */
    static public function getAuthKeyVal($node=1) {/*{{{*/
        $config = ConfigReaderFactory::getInstance()->getConfigReader(OAuthModelConfig::TVB_AUTH_KEY_XML)->getConfig();
        if (empty($config)) return FALSE;
        $n = 1;
        $ret = array();
        foreach($config->tvb_auth as $root) {
            $ret['key'] = (string)$root->key;
            $ret['ver'] = (string)$root->version;
            if ($n == $node) return $ret;
            $n++;
        }
        return $ret;
    }/*}}}*/
    
    /**
     * @method-name : encrypt()
     * @paramter    : (int/string)$param - a string or int .
     * @description : get a encrypt string by $param
     * @return      : string
     * @author      : stephen.mo <stephen.mo@achievo.com>
     * @date        : Mar 15,2011
     */
    static public function encrypt($param) {/*{{{*/
        if (empty($param)) return NULL;
        $config = self::getAuthKeyVal();
        $tvbAuth = new TVBCrypt();
        $now_time = time() + OAuthModelConfig::MOBILE_LOGIN_INFO_EXPIRE_TIME;
        $param = $param.'|'.$now_time;
        $ret = $tvbAuth->encrypt($param,$config['key']);
        return base64_encode($ret);
    }/*}}}*/
    
    /**
     * @method-name : decrypt()
     * @parameter   : (string)$token - the need to decrypt token string.
     * @description : decrypt a token.
     * @return      : array
     * @author      : stephen.mo <stephen.mo@achievo.com>
     * @date        : Mar 16,2011
     */
    static public function decrypt($token) {/*{{{*/
        if (empty($token)) return NULL;
        $config = self::getAuthKeyVal();
        $token = base64_decode($token);
        if (empty($token)) return NULL;
        $tvbAuth = new TVBCrypt();
        $ret = $tvbAuth->decrypt($token,$config['key']);
        $result = explode('|',$ret);
        if (empty($result) || count($result)!=2) return NULL;
        $rec = array('member_id'=>$result[0],'time'=>$result[1]);
        return $rec;
    }/*}}}*/

    /**
     * @method-name : genTVBAuthString()
     * @parameter   : (string)$login_id - the tvb member's login id.
     * @parameter   : (string)$gate_way - the payment gateway,
     * @description : generate a auth string for $gate_way
     * @return      : string
     * @author      : stephen.mo <stephen.mo@achievo.com>
     * @date        : Mar 9,2011
     */
    static public function genTVBAuthString($login_id,$gate_way) {/*{{{*/
        if (empty($login_id) || empty($gate_way)) return FALSE;
        $expire_time = OAuthModelConfig::THIRD_PAYMENT_EXPIRE_TIME;
        $now_time = time()+$expire_time;
        $userInfo = self::getUserInfoByLoginId($login_id);
        if (empty($userInfo) || empty($userInfo->result->member_id)) return FALSE;
        $member_id = $userInfo->result->member_id;
        $encrypt_str = $member_id."|".$now_time."|".$gate_way;
        $config = self::getAuthKeyVal();
        $tvbAuth = new TVBCrypt();
        $ret = $tvbAuth->encrypt($encrypt_str,$config['key']);
        return base64_encode($ret);
    }/*}}}*/

    /**
     * @method-name : decryptTVBAuthString()
     * @parameter   : (string)$tvb_auth - the auth string.
     * @description : decrypt a string by auth key.
     * @return      : array()
     * @author      : stephen.mo <stephen.mo@achievo.com>
     * @date        : Mar 9,2011
     */
    static public function decryptTVBAuthString($tvb_auth) {/*{{{*/
        $ret = array();
        if (empty($tvb_auth)) return $ret;
        $config = self::getAuthKeyVal();
        $auth_str = base64_decode($tvb_auth);
        $tvbAuth = new TVBCrypt();
        $rev = $tvbAuth->decrypt($auth_str,$config['key']);
        if (empty($rev)) return FALSE;
        $data = explode('|',$rev);
        if (empty($data)) return FALSE;
        $ret['member_id'] = (isset($data[0])) ? $data[0] : 0;
        $ret['expire_time'] = (isset($data[1])) ? $data[1] : 0;
        $ret['pg'] = (isset($data[2])) ? $data[2] : NULL;
        return $ret;
    }/*}}}*/
    
    /**
     * @method-name : h3gCheckByApi()
     * @parameter   : (string)$msisdn
     * @parameter   : (string)$login_id.
     * @description : check the h3g user has subscribe by 3G network.
     * @return      : bool
     * @author      : stephen.mo <stephen.mo@achievo.com>
     * @date        : Mar 11,2011
     */
    static public function h3gCheckByApi($msisdn,$login_id) {/*{{{*/
        if (empty($msisdn)) return -1;
        $ret = OAuthModel::getInstance()->h3gCheckByApi($msisdn,$login_id);
        return $ret;
    }/*}}}*/

    /**
     * @method-name : chkTvbAuth()
     * @parameter   : (string)$token - tvb auth token.
     * @description : check it valid?
     * @return      : bool
     * @author      : stephen.mo <stephen.mo@achievo.com>
     * @date        : Mar 16,2011
     */
    static public function chkTvbAuth($token) {/*{{{*/
        if (empty($token)) return FALSE;
        $tokenArr = self::decrypt($token);
        if (empty($tokenArr)) return FALSE;
        if (!isset($tokenArr['member_id']) || empty($tokenArr['member_id'])) return FALSE;
        if (!isset($tokenArr['time']) || empty($tokenArr['time'])) return FALSE;
        if ((time() - $tokenArr['time']) >0) return FALSE;
        return TRUE;
    }/*}}}*/
    
    /**
     * @method-name : getLoginIdByTvbAuth()
     * @parameter   : (string)$token - tvb auth token.
     * @description : decrypt token and get login id.
     * @return      : string
     * @author      : stephen.mo <stephen.mo@achievo.com>
     * @date        : Mar 16,2011
     */
    static public function getLoginIdByTvbAuth($token) {/*{{{*/
        if (!self::chkTvbAuth($token)) return NULL;
        $tokenArr = self::decrypt($token);
        $member_id = $tokenArr['member_id'];
        $userInfo = self::getUserInfoFromMc($member_id);
        $login_id = (isset($userInfo['login_id']) && !empty($userInfo['login_id'])) ? $userInfo['login_id'] : NULL;
        return $login_id;
    }/*}}}*/


}

?>
